package com.example.Utils;

import cn.hutool.core.bean.BeanUtil;

import com.example.model.User;
import com.example.service.impl.UserServiceImpl;
import org.slf4j.Logger;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Map;
import java.util.concurrent.TimeUnit;

public class UserLoginInterceptor implements HandlerInterceptor {

    private StringRedisTemplate stringRedisTemplate;
    private static final Logger logger = LoggerUtils.getLogger(UserServiceImpl.class);

    public UserLoginInterceptor(StringRedisTemplate stringRedisTemplate) {
        this.stringRedisTemplate = stringRedisTemplate;
    }

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        //获取token
        String token = request.getHeader("authorization");
        logger.info("来访的user的token是：{}",token);
        //token不存在，拦截
        if (token == null){
            response.setStatus(401);
            return false;
        }
        //redis获取用户信息
        Map<Object, Object> map = stringRedisTemplate.opsForHash().entries(token);
        map.forEach((k, v) -> {
            logger.info("key : " + k + " Value : " + v);

        });
        //用户是否存在
        //不存在，拦截，状态码：401 未授权
        if (map.isEmpty()){
            response.setStatus(401);
            return false;
        }
        User userDTO = BeanUtil.fillBeanWithMap(map, new User(), false);
        logger.info("userDTO的openid:{}",userDTO.getWechatOpenid());
        //存在，把用户放到ThreadLocal中
        UserHolder.saveUser(userDTO);
        //刷新token有效期
        stringRedisTemplate.expire(token,10, TimeUnit.MINUTES);
        //放行
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        //移除用户
        UserHolder.removeUser();
    }

    public static class Base64DecodedStaticFile implements MultipartFile {
        private byte[] imgContent;

        public Base64DecodedStaticFile(byte[] imgContent) {
            this.imgContent = imgContent;
        }

        @Override
        public String getName() {
            return "filename";
        }

        @Override
        public String getOriginalFilename() {
            return "originalFilename.jpg";
        }

        @Override
        public String getContentType() {
            return "image/jpeg";
        }

        @Override
        public boolean isEmpty() {
            return imgContent == null || imgContent.length == 0;
        }

        @Override
        public long getSize() {
            return imgContent.length;
        }

        @Override
        public byte[] getBytes() throws IOException {
            return imgContent;
        }

        @Override
        public InputStream getInputStream() throws IOException {
            return new ByteArrayInputStream(imgContent);
        }

        @Override
        public void transferTo(java.io.File dest) throws IOException, IllegalStateException {
            // 这里根据你的需求实现文件传输的逻辑
        }
    }
}
